(function (mui, $) {

// 普通页面跳转
$('body').delegate('[data-url]', 'tap', function () {
	app.open($(this).attr('data-url'));
});
// 查看需要登录的页面
$('body').delegate('[data-private]', 'tap', function () {
	if (app.store('member')) {
		app.open($(this).attr('data-private'));
	} else {
		app.open('member.login.html');
	}
});

$('body').delegate('.btn-ally', 'tap', function () {
	var member = app.store('member');
	if (!member) {
		app.open('member.login.html');
	} else if ('9' == member.micro_distribution) {
		// 用户是否能够进行微分销,1:未申请,2:申请中,3申请被拒绝,9:申请通过
		app.open('member.ally.index.html');
	} else {
		app.open('member.ally.join.html');
	}
});

var member = window.member = {};

member.reload = function () {
	call_on_pull_down();
};
// 刷新信息
member.refresh = function (data) {
	app.log('刷新用户数据：', data);
	var cache = app.store('member');
	if (data) {
		$('.avatar img').attr('src', app.avatar(data.avatar));
		$('.nickname').text(cache.nicname || data.username || data.mobile);
		
	} else if (cache) {
		$('.avatar img').attr('src', app.avatar(cache.avatar));
		$('.nickname').text(cache.nicname || cache.username || cache.mobile);
		
	} else {
		$('.avatar img').attr('src', '../image/icon-no-image.png');
		$('.nickname').text('请登录');
	}
};

// 自动登录
member.autologin = function () {
	call_on_pull_down();
}

mui.plusReady(member.autologin);

function call_on_pull_down () {
	var pullrefresh = mui('.container-pull-refresh').pullRefresh();
	
	var cache = app.store('member');
	if (!cache) { pullrefresh.endPulldownToRefresh(); return; }
	
	$.ajax({
		'dataType' : 'json',
		'type'     : 'post',
		'url'      : app.url('App/Sign/Index/autologin'),
		'data'     : {uuid:cache.uuid}
	})
	.fail(function (res) {
		times = 0;
		app.log('自动登录失败：', res);
		app.toast('自动登录失败');
		pullrefresh.endPulldownToRefresh();
	})
	.done(function (res) {
		app.log('自动登录：', res);
		pullrefresh.endPulldownToRefresh();
		//if (500 == res.code) { app.toast('你还未登录'); return; }
		//if (300 == res.code) { app.toast(res.msg); return; }
		//if (200 != res.code) { app.toast('请求失败'); return; }
		//if (res.msg) { app.toast(res.msg); }
		
		if (200 == res.code) {
			app.store('token', res.data.uuid);
			app.store('member', res.data);
			
			member.refresh(res.data);
		}
	})
	;
}
function call_on_pull_up () {
	var pullrefresh = mui('.container-pull-refresh').pullRefresh();
	pullrefresh.endPullupToRefresh();
}
mui.init({
	pullRefresh   : {
		container : '.container-pull-refresh',
		down      : {callback : call_on_pull_down},
		//up        : {callback : call_on_pull_up},
	}
});

})(mui, $);
